using System;

namespace Budgeteer.Services.Common
{
    public static class Time
    {
        public class DisposableTime : IDisposable
        {
            public void Dispose()
            {
                Unfreeze();
            }
        }

        private static DateTime FrozenTime = DateTime.MinValue;

        public static DateTime Now
        {
            get
            {
                return FrozenTime == DateTime.MinValue ? DateTime.Now : FrozenTime;
            }
        }

        public static DisposableTime Freeze()
        {
            if(FrozenTime == DateTime.MinValue)
            {
                FrozenTime = GetCurrentTime();
            }
            return new DisposableTime();
        }

        public static void Unfreeze()
        {
            if(FrozenTime != DateTime.MinValue)
            {
                FrozenTime = DateTime.MinValue;
            }
        }

        private static DateTime GetCurrentTime()
        {
            DateTime now = DateTime.Now;
            now = new DateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second,0,DateTimeKind.Local);
            return now;
        }

        public static DisposableTime Freeze(DateTime expected)
        {
            FrozenTime = expected;
            return new DisposableTime();
        }
    }
}